package com.qf.homework.controller;

import com.alibaba.fastjson.JSONObject;
import com.qf.homework.entity.Category;
import com.qf.homework.service.CategoryService;
import com.qf.homework.service.impl.CategoryServiceImpl;
import com.tomyeung.utils.ResponseUtils;
import com.tomyeung.utils.StatUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

/**
 * @author tomyeung-李尐达
 */
@WebServlet("/Category/add")
public class CategoryController extends HttpServlet {
    private CategoryService service=new CategoryServiceImpl();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        String categoryStr = req.getParameter("category");
        if (categoryStr==null){ ResponseUtils.fail(resp, StatUtil.DATA_NULL); }
        else {
            try {
                Category category = JSONObject.parseObject(categoryStr, Category.class);
                int count = service.add(category);
                if (count==1){ResponseUtils.success(resp,StatUtil.SUCCESS);}
                else { ResponseUtils.fail(resp,StatUtil.INTERNET_ERR);}
            } catch (SQLException troubles) {
                troubles.printStackTrace();
                ResponseUtils.fail(resp,StatUtil.SERVER_BUST);
            }
        }
    }
}
